package controller;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;

import data.Data;

public class Analytics {
	public static void main(String[] args) {
		DBCollection collection = Data.data("users");
		DBCollection coll = Data.data("urlCraw");
		DBCursor cursor = collection.find();
		int k = 0;
		String str = "";
		
		String content = Utils.GetHtml("http://localhost:8888/mail.jsp", "utf-8");
		
		while (cursor.hasNext()) {
			DBObject dbObject = (DBObject) cursor.next();
			int cout = coll.find(new BasicDBObject("username",dbObject.get("username"))).count();
			if(cout!=0)
			{
				k++;
//				str+=dbObject.get("email")+"|"+dbObject.get("username")+"\n";
				String email = dbObject.get("email").toString();
				try {
					URL url = new URL("http://yoospain.appspot.com/sendemail");
		            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		            connection.setDoOutput(true);
		            connection.setRequestMethod("POST");
		            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
		            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
		            writer.write("email="+email);
		            writer.write("&name_email="+email);
		            writer.write("&from_email=admin@hatforrent.com");
		            writer.write("&subject=Make Fresh Contents for your site by Hatforrent service.");
		            writer.write("&content="+content.replace("[customer]", dbObject.get("username").toString()));
		            writer.close();
		    
		            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
		            	 BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
		            }
				} catch (Exception e) {
					// TODO: handle exception
				}
				System.out.println(dbObject.get("username")+"|"+cout);
			}
			
		}
//		try {
//			// Create file
//			FileWriter fstreams = new FileWriter("out.txt");
//			BufferedWriter out = new BufferedWriter(fstreams);
//			out.write(str);
//			// Close the output stream
//			out.close();
//		} catch (Exception e) {// Catch exception if any
//			System.err.println("Error: " + e.getMessage());
//		}
		System.out.println(k+" user");
	}
}
